package io.github.zerobyteword.springfasterstartup;

import io.github.zerobyteword.springfasterstartup.config.AsyncInitProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;

public class AsyncInitApplicationInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    private static final Logger logger = LoggerFactory.getLogger(AsyncInitApplicationInitializer.class);

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        AsyncInitProperties asyncInitProperties = Binder.get(applicationContext.getEnvironment()).bind("spring.easy.faster", AsyncInitProperties.class).get();
        if (asyncInitProperties.isEnabled()) {
            logger.info("spring-faster-startup 启动!");
            AsyncInitManager asyncInitManager = new AsyncInitManager(asyncInitProperties, new AsyncInitProperties.InnerProperties());
            AsyncInitBeanPostProcessor asyncInitBeanPostProcessor = new AsyncInitBeanPostProcessor(asyncInitManager);
            asyncInitBeanPostProcessor.setBeanFactory(applicationContext.getBeanFactory());
            AsyncInitListener asyncInitListener = new AsyncInitListener(asyncInitManager, applicationContext);
            applicationContext.getBeanFactory().registerSingleton("asyncInitListener", asyncInitListener);
            applicationContext.getBeanFactory().registerSingleton("asyncInitBeanPostProcessor", asyncInitBeanPostProcessor);
        }
    }
}
